/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package warehouse;

import entity.CategoryLocal;
import entity.CategoryLocalHome;
import entity.CommodityLocal;
import entity.CommodityLocalHome;
import helper.SimpleJSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import transfer.Commodity;
import transfer.CommodityCategory;

/**
 *
 * @author rebelizant
 */
public class CommodityOperation extends HttpServlet {
    
    public static final String idParameter = "id";
    public static final String actionParameter = "action";
    public static final String idCategory = "categoryId";
    public static final String answer = "answer";
    public static final String ok = "ok";
    public static final String wrong = "wrong";
    public static final String editAction = "edit";
    public static final String deleteAction = "delete";
    public static final String createAction = "create";
    public static final String splitter = ";";
    public static final String idCommodity = "idCommodity";
    
    public static final String nameParameter = "name";
    public static final String priceParameter = "price";
    public static final String descriptionParameter = "description";
    
    private Integer createdCommodityId = new Integer(0);

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter(actionParameter);
        if (action.equals(editAction)) {
            editCommodity(request, response);
        }
        if (action.equals(createAction)) {
            createCommodity(request, response);
        }
        if (action.equals(deleteAction)) {
            deleteCommodities(request, response);
        }
    }
    
    private void deleteCommodities(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idsString = request.getParameter(idParameter);        
        String[] ids = idsString.split(splitter);
        Integer[] idsNumber = new Integer[ids.length];        
        for (int i = 0; i < ids.length; i++) {
            idsNumber[i] = new Integer(ids[i]);
        }
        try {
            Context c = new InitialContext();
            CommodityLocalHome commodityHome = (CommodityLocalHome) c.lookup("java:comp/env/Commodity");
            for (int i = 0; i < idsNumber.length; i++) {
                CommodityLocal commodityLocal = commodityHome.findByPrimaryKey(idsNumber[i]);
                Commodity commodity = commodityLocal.getCommodity();
                commodity.setOutOfProduction(Boolean.TRUE);
                commodityLocal.setCommodity(commodity);
            }
        } catch (NamingException exc) {
            exc.printStackTrace();
        } catch (FinderException exc) {
            exc.printStackTrace();
        }
    }
    
    private void editCommodity(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Integer id = new Integer(request.getParameter(idParameter));        
        try {
            Context c = new InitialContext();
            CommodityLocalHome commodityHome = (CommodityLocalHome) c.lookup("java:comp/env/Commodity");           
            CommodityLocal commodityLocal = commodityHome.findByPrimaryKey(id);
            Commodity commodity = commodityLocal.getCommodity();
            Double price = new Double(request.getParameter(priceParameter));
            if (!price.equals(commodity.getPrice())) {
                CommodityLocal cl = createCommodity(request, response);
                Commodity comm = cl.getCommodity();
                comm.setImage(commodity.getImage());
                cl.setCommodity(comm);
                commodity.setOutOfProduction(Boolean.TRUE);
                commodityLocal.setCommodity(commodity);
                SimpleJSONObject json = new SimpleJSONObject();
                json.addProperty(idCommodity, cl.getCommodity().getIdCommodity().toString());
                sendJSON(json, response);
            } else {
                commodity.setNameCommodity(request.getParameter(nameParameter));
                commodity.setDescription(request.getParameter(descriptionParameter));            
                commodityLocal.setCommodity(commodity);
            }            
        } catch (NamingException exc) {
            exc.printStackTrace();
        } catch (FinderException exc) {
            exc.printStackTrace();
        }
    }
    
    private CommodityLocal createCommodity(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter(nameParameter);
        Double price = new Double(request.getParameter(priceParameter));
        Integer catId = new Integer(request.getParameter(idCategory));
        String description = request.getParameter(descriptionParameter);
        CommodityLocal cl = null;
        try {
            Context c = new InitialContext();
            CommodityLocalHome commodityHome = (CommodityLocalHome) c.lookup("java:comp/env/Commodity");
            CategoryLocalHome categoryHome = (CategoryLocalHome) c.lookup("java:comp/env/Category");
            CategoryLocal categoryLocal = categoryHome.findByPrimaryKey(catId);
            Commodity commodity = new Commodity();
            commodity.setNameCommodity(name);
            commodity.setPrice(price);
            commodity.setDescription(description);
            commodity.setPopularity(new Integer(0));
            commodity.setOutOfProduction(Boolean.FALSE);            
            commodity.setCategory(categoryLocal.getCategory());
            cl = commodityHome.create(commodity);
            SimpleJSONObject json = new SimpleJSONObject();
            json.addProperty(idCommodity, cl.getCommodity().getIdCommodity().toString());
            sendJSON(json, response);
        } catch (NamingException exc) {
            exc.printStackTrace();
        } catch (CreateException ex) {
            ex.printStackTrace();
        } catch (FinderException ex) {
            ex.printStackTrace();
        } finally {
            return cl;
        }
    }
    
    private static void sendJSON(SimpleJSONObject json, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.println(json);
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
